package com.godme.structure;


public class Queue {

    final DoubleNode head = new DoubleNode(-1);
    final DoubleNode tail = new DoubleNode(-1);

    public Queue(){
        head.next = tail;
    }


    public void add(int value){
        DoubleNode cursor = head;
        while (cursor.next != tail){
            cursor = cursor.next;
        }
        DoubleNode addNode = new DoubleNode(value);
        connectNodes(cursor, addNode, cursor.next);
    }

    public int poll(){
        DoubleNode targetNode = head.next;
        connectNodes(head, targetNode.next);
        return targetNode.value;
    }

    public boolean isEmpty(){
        return head.next == tail;
    }

    public void connectNodes(DoubleNode ...nodes){
        DoubleNode lastNode = nodes[0];
        DoubleNode currentNode;
        for (int i = 1; i < nodes.length; i++) {
            currentNode = nodes[i];
            lastNode.next = currentNode;
            currentNode.prev = lastNode;
            lastNode = currentNode;
        }
    }


    public static void main(String[] args) {
        Queue queue = new Queue();
        for (int i = 0; i < 10; i++) {
            queue.add(i);
        }
        while(!queue.isEmpty()){
            System.err.println(queue.poll());
        }

    }




    static class DoubleNode{
        int value;
        DoubleNode prev;
        DoubleNode next;

        public DoubleNode(int value){
            this.value = value;
        }
    }

}
